using System;
using System.Net.Mail;
using System.Text.RegularExpressions;

namespace Framework.Library.Core.Utils.Email
{
    public static class EmailUtils
    {
        /// <summary>
        /// Ensures the line feeds. See http://cr.yp.to/docs/smtplf.html and 822bis section 2.3.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string EnsureLineFeeds(string value)
        {
            return Regex.Replace(value, "(?<!\r)\n", "\r\n",
                                 RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// Parses the comma delimited email addresses.
        /// </summary>
        /// <param name="emailAddresses">The email addresses.</param>
        /// <returns></returns>
        public static MailAddressCollection ParseEmailAddresses(string emailAddresses)
        {
            try
            {
                var mailAddressCollection = new MailAddressCollection();

                if (!string.IsNullOrEmpty(emailAddresses))
                    mailAddressCollection.Add(emailAddresses);

                return mailAddressCollection;
            }
            catch (FormatException e)
            {
                throw new FormatException("Error parsing email addresses: " + emailAddresses, e);
            }
        }
    }
}